package zhh.tangbao.websocket.client;

import cn.hutool.core.lang.Assert;
import zhh.tangbao.system.utils.ApplicationContextUtil;
import zhh.tangbao.websocket.service.WebSocketService;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *     描述
 * </p>
 * @author 粥灰灰
 * <p>2023/4/20</p>
 */
public abstract class WebSocketClient {

    /** 双向锁定，只有client保存ID才方便知晓发消息过来的是哪个用户 */
    protected String id;

    /** websocket */
    protected Session session;

    protected final Map<String, WebSocketService> serviceStrategy = ApplicationContextUtil.getBeanMap(WebSocketService.class);

    protected WebSocketService getStrategy(String strategyType) {
        return serviceStrategy.get(strategyType);
    }

    public String getId() {
        return id;
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public boolean isOpen() {
        return this.session.isOpen();
    }

    public abstract void onOpen(Session session, @PathParam("token") String token, @PathParam("key") String key);

    public abstract void onClose();

    public abstract void onError(Throwable throwable);

    public abstract void onMessage(String message);

    public void removeClient(String strategyType, String id) {
        WebSocketService strategy = getStrategy(strategyType);
        Assert.notNull(strategy, "该功能未实现");
        strategy.removeClient(id);
    }

    public void addClient(String strategyType, String id, WebSocketClient client) {
        WebSocketService strategy = getStrategy(strategyType);
        Assert.notNull(strategy, "该功能未实现");
        strategy.addClient(id, client);
    }


}
